package com.uyayo.oms.system.controller;

import com.uyayo.framework.common.annotation.MethodName;
import com.uyayo.framework.common.exception.CodeMultipleException;
import com.uyayo.framework.message.model.Result;
import com.uyayo.framework.common.util.CodeUtil;
import com.uyayo.oms.system.biz.ParamBiz;
import com.uyayo.oms.system.vo.SysParamVO;
import com.uyayo.framework.pagehelper.pojo.PageBean;
import com.uyayo.framework.pagehelper.pojo.PageResult;
import com.uyayo.system.config.entity.SysParam;
import com.uyayo.system.config.model.SysParamCondition;
import com.uyayo.system.config.service.SysParamService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


/**
 * 
 * <p>
 * Title: ParamsController
 * </p>
 * <p>
 * Description:全局参数的controller
 * </p>
 * <p>
 * Company: www.lelekeji.com
 * </p>
 * 
 * @author 乐乐科技.胡逢君
 * @date 2015-4-13下午4:03:35
 * @version 1.0
 */
@Controller
@RequestMapping("/system/config/param")
public class SysParamController {

	private final SysParamService paramsService;
	
	private final ParamBiz paramBiz;

	private  final MessageSource messageSource;

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	public SysParamController(ParamBiz paramBiz, SysParamService paramsService, MessageSource messageSource) {
		this.paramBiz = paramBiz;
		this.paramsService = paramsService;
		this.messageSource = messageSource;
	}

	@MethodName(value="系统管理->系统配置->全局参数管理")
	@RequestMapping(value="index",method=RequestMethod.GET)
	public String index() throws Exception {
		return paramBiz.getManagerTemplatesPrefix()+"system/config/param/index";
	}

	@ResponseBody
	@RequestMapping(value="grid",method=RequestMethod.GET)
	@MethodName(value="系统管理->系统配置->全局参数管理->查询列表",type=2)
	public PageResult<SysParam> selectParams(@RequestParam(value = "offset",required = false, defaultValue = "1") Integer start, //第多少行之后开始
            @RequestParam(value = "limit", required = false, defaultValue = "10") Integer pageSize,String sort,String order,HttpServletRequest request,SysParamCondition sysParamCondition) throws Exception {
		PageBean<SysParam> pageBean=new PageBean<>();
		try {
			pageBean = paramsService.selectParams((start / pageSize) + 1, pageSize,sort,order,sysParamCondition);
		} catch (Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
		}
		PageResult<SysParam> pageResult = new PageResult<>();
		pageResult.setRows(pageBean.getList());
		pageResult.setTotal(pageBean.getTotalCount());
		return pageResult;
		
	}
	
	/**
	 * 进入添加全局参数页面
	 * @param modelAndView
	 * @return
	 */
	@RequestMapping(value = "add", method = RequestMethod.GET)
	public ModelAndView add(ModelAndView modelAndView) {
		
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"system/config/param/add");
		return modelAndView;
	}
	
	/**
	 * 新建一个全局参数
	 */
	@ResponseBody
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@MethodName(value="系统管理->系统配置->全局参数管理->保存全局参数",type=2)
	public Result add(HttpServletRequest request, @Validated SysParamVO sysParamVo , Errors errors) {
		try {
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
		    }

			SysParam sysParam = new SysParam();
			sysParam.setId(CodeUtil.getTimeSequenceAsRandomCode());
			sysParam.setCode(sysParamVo.getCode());
			sysParam.setName(sysParamVo.getName());
			sysParam.setValue(sysParamVo.getValue());
			sysParam.setSeq(sysParamVo.getSeq());
			sysParam.setDescription(sysParamVo.getDescription());
			sysParam.setCreatedTime(new Date());
			sysParam.setRemark(sysParamVo.getRemark());
			paramsService.saveParams(sysParam);
		} catch (CodeMultipleException e){
			String message = messageSource.getMessage("code.multiple.error",new Object[]{}, request.getLocale());
			logger.info(message,e.getMessage());
			return Result.error(400,message);
		}  catch (Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.error(500,message);
		}
		String message = messageSource.getMessage("save.success",new Object[]{}, request.getLocale());
		return Result.success(200,message);
	}
	
	
	/**
	 * 进入全局参数查看页面
	 */
	@MethodName(value="系统管理->系统配置->全局参数管理->查看",type=2)
	@RequestMapping(value = "view", method = RequestMethod.GET)
	public ModelAndView show(ModelAndView modelAndView,HttpServletRequest request,String id) {
		SysParam sysParam = new SysParam();
		try {
			sysParam = paramsService.getSysParamsById(id);
		} catch (Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
		}
		modelAndView.addObject("sysParam",sysParam);
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"system/config/param/view");
		return modelAndView;
	}
	
	
	/**
	 * 进入角色修改页面
	 */
	@RequestMapping(value = "update", method = RequestMethod.GET)
	public ModelAndView update(ModelAndView modelAndView,HttpServletRequest request,String id) {
		SysParam sysParam = new SysParam();
		try {
			sysParam = paramsService.getSysParamsById(id);
		} catch (Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
		}
		modelAndView.addObject("sysParam",sysParam);
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"system/config/param/edit");
		return modelAndView;
	}
	
	/**
	 * 修改一个全局参数
	 */
	@ResponseBody
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@MethodName(value="系统管理->系统配置->全局参数管理->修改全局参数",type=2)
	synchronized public Result updateParams(HttpServletRequest request,@Validated SysParamVO sysParamVo , Errors errors) {
		try {
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
		    }
			SysParam sysParam = new SysParam();
			sysParam.setId(sysParamVo.getId());
			sysParam.setCode(sysParamVo.getCode());
			sysParam.setName(sysParamVo.getName());
			sysParam.setValue(sysParamVo.getValue());
			sysParam.setSeq(sysParamVo.getSeq());
			sysParam.setDescription(sysParamVo.getDescription());
			sysParam.setModifiedTime(new Date());
			sysParam.setRemark(sysParamVo.getRemark());
			paramsService.updateParam(sysParam);
		}catch (CodeMultipleException e){
			String message = messageSource.getMessage("code.multiple.error",new Object[]{}, request.getLocale());
			logger.info(message,e.getMessage());
			return Result.error(400,message);
		}  catch (Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.error(500,message);
		}
		String message = messageSource.getMessage("save.success",new Object[]{}, request.getLocale());
		return Result.success(200,message);
	}

	
	/**
	 * 删除记录
	 */
	@MethodName(value="系统管理->配置管理->全局参数管理->删除",type=2)
	@ResponseBody
	@RequestMapping(value="delete",method=RequestMethod.DELETE)
	public Result deleteParam(HttpServletRequest request, String id) {

		try {
			if (id==null) {
				String message = messageSource.getMessage("parameter.error",new Object[]{}, request.getLocale());
				logger.error(message);
				return Result.error(400,message);
			}
			int deleteCount = paramsService.deleteParamsById(id);
			if(deleteCount<=0){
				String message = messageSource.getMessage("delete.fail",new Object[]{}, request.getLocale());
				logger.error(message);
				return Result.error(400,message);
			}
		} catch(Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.error(500,message);
		}
		String message = messageSource.getMessage("delete.success",new Object[]{}, request.getLocale());
		logger.error(message);
		return Result.success(200,message);

	}
	

	
}
